document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const certTypeRadios = document.querySelectorAll('input[name="certType"]');
    const barcodeLength = document.getElementById('barcodeLength');
    const generateBtn = document.getElementById('generateBtn');
    const printBtn = document.getElementById('printBtn');
    const barcodeTable = document.querySelector('#barcodeTable tbody');
    const loadingOverlay = document.getElementById('loadingOverlay');

    // 更新条码长度显示
    function updateBarcodeLength() {
        const selectedValue = document.querySelector('input[name="certType"]:checked').value;
        barcodeLength.textContent = selectedValue;
    }

    // 初始化
    updateBarcodeLength();

    // 监听单选按钮变化
    certTypeRadios.forEach(radio => {
        radio.addEventListener('change', updateBarcodeLength);
    });

    // 生成条码数据按钮
    generateBtn.addEventListener('click', function() {
        const selectedType = document.querySelector('input[name="certType"]:checked').value;
        const startNum = document.getElementById('startNum').value;
        const buyer = document.getElementById('buyer').value;
        const batch = document.getElementById('batch').value;
        const sample = document.getElementById('sample').value;
        const origin = document.getElementById('origin').value;
        const bag = document.getElementById('bag').value;
        const sampleDate = document.getElementById('sampleDate').value;

        // 清空表格
        barcodeTable.innerHTML = '';

        // 验证输入
        if (!startNum) {
            alert('请输入条码起始编号');
            return;
        }

        if (!/^\d+$/.test(startNum)) {
            alert('条码起始编号必须为数字');
            return;
        }

        if (startNum.length !== parseInt(selectedType)) {
            alert(`条码起始编号长度必须为${selectedType}位`);
            return;
        }

        // 生成10个条码数据
        for (let i = 0; i < 10; i++) {
            const barcodeNum = String(parseInt(startNum) + i).padStart(selectedType, '0');

            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${barcodeNum}</td>
                <td>${buyer}</td>
                <td>${batch}</td>
                <td>${origin}</td>
                <td>${bag}</td>
                <td>${sampleDate}</td>
            `;

            barcodeTable.appendChild(row);
        }
    });

    // 打印按钮
    printBtn.addEventListener('click', function() {
        const selectedType = document.querySelector('input[name="certType"]:checked').value;
        const startNum = document.getElementById('startNum').value;
        const buyer = document.getElementById('buyer').value;
        const batch = document.getElementById('batch').value;
        const sample = document.getElementById('sample').value;
        const origin = document.getElementById('origin').value;
        const bag = document.getElementById('bag').value;
        const sampleDate = document.getElementById('sampleDate').value;

        // 验证输入
        if (!startNum) {
            alert('请输入条码起始编号');
            return;
        }

        if (!/^\d+$/.test(startNum)) {
            alert('条码起始编号必须为数字');
            return;
        }

        if (startNum.length !== parseInt(selectedType)) {
            alert(`条码起始编号长度必须为${selectedType}位`);
            return;
        }

        // 显示加载动画
        loadingOverlay.style.display = 'flex';

        // 准备发送到后端的数据
        const data = {
            certType: selectedType,
            startNum: startNum,
            buyer: buyer,
            batch: batch,
            sample: sample,
            origin: origin,
            bag: bag,
            sampleDate: sampleDate
        };

        // 发送请求到后端
        fetch('/data_show/generate_barcodes/generate_barcodes_list', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw new Error(err.error) });
            }
            return response.blob();
        })
        .then(blob => {
            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `条码打印_${new Date().toISOString().replace(/[:.]/g, '-')}.pdf`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        })
        .catch(error => {
            alert(`生成条码失败: ${error.message}`);
        })
        .finally(() => {
            // 隐藏加载动画
            loadingOverlay.style.display = 'none';
        });
    });
});